/*
 * @Author: zhousg
 * @Date: 2020-09-15 17:45:19
 * @Last Modified by: zhousg
 * @Last Modified time: 2021-01-23 18:45:44
 */

import axios from 'axios'
import store from '@/store'
import router from '@/router'

const instance = axios.create({
  // baseURL: 'https://mock.boxuegu.com/mock/1175/',
  baseURL: 'http://pcapi-xiaotuxian-front.itheima.net/',
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(config => {
  config.headers['souce-client'] = 'pc'
  // 如果token存在在请求头携带
  const { token } = store.state.user
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
}, e => Promise.reject(e))

// 响应拦截器
instance.interceptors.response.use(res => res, e => {
  // 在某一个页面，如果登录失效拦截到登录，且在地址栏携带返回页面的路径
  if (e.response && e.response.status === 401) {
    const targetUrl = router.currentRoute.fullPath
    router.push('/login', { query: { redirectUrl: encodeURIComponent(targetUrl) } })
  }
  return Promise.reject(e)
})

export default instance
